<template>
    <div class="container">
        <div class="nav">
            <div @click="toHomePage">首页</div>
            <div>
                分类
                <n-popselect v-model:value="selectedCategory" :options="categorySelectOptions"
                    @update:value="screenCategory" size="medium" scrollable>
                    <n-button type="tertiary" size="tiny">
                        {{ categoryName || '全部' }}
                    </n-button>
                </n-popselect>
            </div>
            <div @click="toDashboard">后台</div>
        </div>
        <n-divider />

        <n-flex style="margin-bottom: 15px;">
            <n-input v-model:value="pageInfo.keyWord" type="text" :style="{ width: '33%' }" maxlength="30" show-count
                clearable placeholder="请输入关键字..."></n-input>
            <n-button type="primary" ghost @click="searchFor()">搜索</n-button>
        </n-flex>

        <div class="blogList">
            <div v-for="(blog, index) in blogListIfo">
                <n-card :title="blog.title" hoverable style="margin-bottom: 15px; cursor: pointer;" @click="toDetail(blog)">
                    <n-ellipsis :line-clamp="2" :tooltip="false">
                        {{ blog.content }}
                    </n-ellipsis>
                    <template #footer>
                        <n-flex :align="'center'">
                            <div>发布时间: {{ blog.update_time }}</div>
                        </n-flex>
                    </template>
                </n-card>
            </div>
            <n-pagination v-model:page="pageInfo.page" :page-count="pageInfo.pageCount" @update:page="toPage" />
        </div>

        <n-divider />
        <div class="footer">
            <div>Power by X000X</div>
            <div>XICP备0000x号-1</div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, inject, onMounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { AdminStore } from "../stores/AdminStore";

onMounted(() => {
    loadCategoryDatas()
    loadBlogDatas()
})

const router = useRouter()
const route = useRoute()

const adminStore = AdminStore()

const axios = inject('axios')
const message = inject('message')

const categorySelectOptions = ref([])
const selectedCategory = ref([])
const blogListIfo = ref([])
const pageInfo = reactive({
    page: 1, // 第几页
    pageSize: 5, // 每页几条数据
    count: 0,// 全页总数据
    pageCount: 0, // 有几页
    keyWord: "",
    categoryId: 0
})

const screenCategory = (categoryId) => {
    pageInfo.categoryId = categoryId
    loadBlogDatas()
}

const searchFor = () => {
    loadBlogDatas()
}

const toDetail = (blog) => {
    router.push({ path: "/detail", query: { id: blog.id } })
}

const toHomePage = () => {
    router.push('/')
}

const toDashboard = () => {
    router.push('/login')
}

const toScrollTop = () => {
    if (document.body.scrollTop) {
        document.body.scrollTop = 0
    } else {
        document.documentElement.scrollTop = 0
    }
}

const toPage = (pageNum) => {
    pageInfo.page = pageNum
    loadBlogDatas()
}

const categoryName = computed(() => {
    let selectedOption = categorySelectOptions.value.find((option) => {
        return option.value == selectedCategory.value
    })
    // console.log(selectedOption);
    return selectedOption ? selectedOption.label : ""
})

const loadCategoryDatas = async () => {
    try {
        let res = await axios.get("/api/category/list")
        console.log(res.data._dbres);
        categorySelectOptions.value = res.data._dbres.map(item => {
            return {
                label: item.name,
                value: item.id
            }
        })
        categorySelectOptions.value.unshift({ label: '全部', value: 0 })
    } catch (error) {
        console.log(error.response.data);
        message.error(error.response.data.msg);
    }
}

const loadBlogDatas = async () => {
    try {
        let res = await axios.get("/api/blog/list", { params: { page: pageInfo.page, pageSize: pageInfo.pageSize, keyword: pageInfo.keyWord, category_id: pageInfo.categoryId } })
        let temp_rows = res.data.data
        for (let row of temp_rows) {
            row.content += '...'
            row.update_time = new Date(row.update_time).toLocaleString()
        }
        pageInfo.count = res.data.count
        pageInfo.pageCount = Math.ceil(pageInfo.count / pageInfo.pageSize)
        blogListIfo.value = temp_rows
        toScrollTop()
        // message.success("数据获取成功");
    } catch (error) {
        console.log(error);
        message.error("数据获取失败");
    }
}
</script>

<style lang="scss" scoped>
.container {
    width: 1200px;
    margin: 0 auto;

    .nav {
        display: flex;
        font-size: 20px;
        padding-top: 20px;
        color: 口#64676a;

        div {
            cursor: pointer;
            margin-right: 15px;

            &:hover {
                color: #f60;
            }
        }
    }

    .footer {
        text-align: center;
        line-height: 25px;
        color: #0a0a0a;
    }
}
</style>